import akshare as ak
import pandas as pd
import time
import os

# 读取包含股票代码和简称的 CSV 文件
stock_list_df = pd.read_csv("code_name.csv", dtype={"股票代码": str})

# 输出文件路径
output_file = "stock_info.csv"

# 标记是否已写入过表头
header_written = os.path.exists(output_file)

for idx, row in stock_list_df.iterrows():
    symbol = row["股票代码"]
    stock_name = row["股票简称"]
    try:
        stock_info = ak.stock_individual_info_em(symbol=symbol)
        row_dict = dict(zip(stock_info["item"], stock_info["value"]))

        # 添加代码和简称
        row_dict["股票代码"] = symbol
        row_dict["股票简称"] = stock_name

        # 重命名“最新”为“最新价格”
        if "最新" in row_dict:
            row_dict["最新价格"] = row_dict.pop("最新")

        # 转为 DataFrame（单行）
        df_row = pd.DataFrame([row_dict])

        # 调整“最新价格”列的位置
        cols = df_row.columns.tolist()
        if "股票简称" in cols and "最新价格" in cols:
            cols.remove("最新价格")
            idx_pos = cols.index("股票简称") + 1
            cols.insert(idx_pos, "最新价格")
            df_row = df_row[cols]

        # 写入文件（首次写入带 header，之后不带）
        df_row.to_csv(output_file, mode='a', header=not header_written, index=False, encoding='utf-8-sig')
        header_written = True

        time.sleep(1)  # 避免请求过快

    except Exception as e:
        print(f"获取 {symbol} 数据失败：{e}")
